/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Cordic {
    public static long timeInUs() {
        return System.nanoTime();
    }

    public static double fixed(double x) {
        return x * 65536.0;
    }

    public static double floatVal(double x) {
        return x / 65536.0;
    }

    public static final double ag_count = 0.6072529350;

    public static double cordicsincos(double target, double[] angles) {
        double x = 0.0;
        double y = 0.0;
        double targetAngle = 0.0;
        double currAngle = 0.0;
        int step;

        x = fixed(ag_count);
        targetAngle = fixed(target);
        currAngle = 0.0;
        for (step = 0; step < 12; step++) {
            double newX = 0.0;
            if (targetAngle > currAngle) {
                newX = x - ((long) y >> step);
                y = ((long) x >> step) + y;
                x = newX;
                currAngle += angles[step];
            } else {
                newX = x + ((long) y >> step);
                y = -((long) x >> step) + y;
                x = newX;
                currAngle -= angles[step];
            }
        }
        return floatVal(x) * floatVal(y);
    }

}
/*
 * @State
 * @Tags Jetstream2
 */
class Benchmark {
   public static void main(String[] args) {
       runCordic();
   }
   /*
    *@Benchmark
    */
   public static void runCordic() {
       double res = 0.0;
       double Target = 28.027;
       double input = 150000;
       final double[] angles = new double[] {
               Cordic.fixed(45.0), Cordic.fixed(26.565), Cordic.fixed(14.0362), Cordic.fixed(7.12502),
               Cordic.fixed(3.57633), Cordic.fixed(1.78991), Cordic.fixed(0.895174), Cordic.fixed(0.447614),
               Cordic.fixed(0.223811), Cordic.fixed(0.111906), Cordic.fixed(0.055953),
               Cordic.fixed(0.027977)
       };
       long start = Cordic.timeInUs();
       for (int i = 0; i < input; i++) {
           res += Cordic.cordicsincos(Target + i, angles);
       }
       long end = Cordic.timeInUs();
       long time = (end - start);
       System.out.println("res: "+res);
       System.out.println("Numerical Calculation - RunCordic:" + time / 1_000_000.0 + "ms");
   }
}